package com.modul.simpleLock.lockservice;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/6 11:51
 * @Description: 简单锁的实现逻辑
 */
@Slf4j
public class SimpleRedisLock implements RedisLock {

    private StringRedisTemplate redisTemplate;
    private String key;

    private final String VALUE_PREFIX = UUID.randomUUID().toString();

    //创建SimpleRedisLock这个类的实例
    public SimpleRedisLock(StringRedisTemplate redisTemplate, String key) {
        this.redisTemplate = redisTemplate;
        this.key = key;
    }


    @Transactional(rollbackFor = Exception.class)
    // 尝试获取锁
    @Override
    public Boolean tryLock(long releaseTime) {

        // 当前线程唯一标识
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        log.info("当前线程的唯一标识：[{}]", value);
        // 尝试重redis中获取锁 并设置过期时间
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        log.info("aBoolean:[{}]",aBoolean);
        String s = redisTemplate.opsForValue().get(key);
        System.out.println("s = " + s);
        return BooleanUtils.isTrue(aBoolean);
    }


    // 释放锁
    @Override
    public void unlock() {
        // 先获取当前线程的唯一标识
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        String s = redisTemplate.opsForValue().get(key);
        if (StringUtils.equals(value, s)) redisTemplate.delete(key);
    }

    /**
     * 根据key 判断是否存在值
     *
     * @param key
     * @return true 存在 false 不存在
     */
    @Override
    public Boolean getLock(String key) {
        String value = redisTemplate.opsForValue().get(key);
        return StringUtils.isNotBlank(value) ? BooleanUtils.isTrue(true) : BooleanUtils.isFalse(false);


    }


}
